package cn.ybz21.hibot.resource;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import cn.ybz21.hibot.bean.App;
import cn.ybz21.hibot.bean.ResultCode;
import cn.ybz21.hibot.dao.AppDAO;
import cn.ybz21.hibot.util.MQTTPublisher;

import com.google.gson.Gson;

@Path("/app")
public class AppResource {

	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String getDefaultTask() {
		return "app  center";
	}

	@GET
	@Path("/list")
	@Produces(MediaType.APPLICATION_JSON)
	public List<App> getAppList(@QueryParam(value = "startPage") int startPage,
			@QueryParam(value = "pageSize") int pageSize) {
		if (pageSize == 0) {
			pageSize = 100;
			startPage = 1;
		}
		return new AppDAO().queryApps(startPage, pageSize);
	}

	@GET
	@Path("/download/appId/{appId}/robotIds/{robotIds}")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode push(@PathParam("robotIds") String robotIds,
			@PathParam("appId") String appId) {
		return sendAppMsg(robotIds, appId, "downloadApp");
	}

	@GET
	@Path("/start/appId/{appId}/robotIds/{robotIds}")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode startApp(@PathParam("robotIds") String robotIds,
			@PathParam("appId") String appId) {
		return sendAppMsg(robotIds, appId, "startApp");
	}

	@GET
	@Path("/stop/appId/{appId}/robotIds/{robotIds}")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode stopApp(@PathParam("robotIds") String robotIds,
			@PathParam("appId") String appId) {
		return sendAppMsg(robotIds, appId, "stopApp");
	}

	private ResultCode sendAppMsg(String robotIds, String appId, String topic) {
		App app = new AppDAO().queryAppById(appId);
		String ids[] = robotIds.split(",");
		for (int j = 0; j < ids.length; j++) {
			MQTTPublisher.postMessage(topic + "/" + ids[j],
					new Gson().toJson(app));
		}
		String time = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss-SSS")
				.format(new Date());
		System.out.println("server push app, time:" + time);
		ResultCode rCode = new ResultCode(0);
		return rCode;
	}
}